<?php
$dbname="172.16.250.169/orcl";
$dbuser="libsys";
$dbpassword="libsys";
$campusapp_url="https://eaiapp.ccom.edu.cn";
$campusapp_appid="200200405134542698";
$campusapp_appsecret="smeyasjgy1tksxm9bmpv5gnhjbaf6ngu";

$ecard_dbname="10.10.10.114/middle";
$ecard_user="middle";
$ecard_password="middle";

header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header("Pragma: no-cache");

if($_SERVER['REQUEST_METHOD']=='GET') {
	if(!array_key_exists('code', $_GET)) $should_redirect=1;
	else {
		$url=sprintf("%s/api/third/get-token", $campusapp_url);
		$opts=['appid'=>$campusapp_appid, 'appsecret'=>$campusapp_appsecret];
		$ch = curl_init($url.'?'.http_build_query($opts));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		$r=curl_exec($ch);
		$result=json_decode($r);
		if($r===FALSE || $result->e || empty($result->d->access_token)) {
			http_response_code(500); exit;
		}
		curl_close($ch);

		$url=sprintf("%s/uc/api/oauth/user-by-code", $campusapp_url);
		$opts=['code'=>$_GET['code'], 'access_token'=>$result->d->access_token];
		$ch = curl_init($url.'?'.http_build_query($opts));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		$r=curl_exec($ch);
		$result=json_decode($r);
		if($r===FALSE || $result->e || empty($result->d->role->number)) {
			$should_redirect=1;
		} else {
			curl_close($ch);
			$uid=$result->d->role->number;
			$uname=$result->d->realname;
		}
	}

	if($should_redirect==1) {
		$url=sprintf('Location: %s/uc/api/oauth/index?redirect=%s&appid=%s',
			$campusapp_url,
			urlencode(sprintf('%s://%s%s',$_SERVER['HTTPS']?'https':'http',$_SERVER['HTTP_HOST'],$_SERVER['REQUEST_URI'])),
			$campusapp_appid
		);
        	header($url, TRUE, 302);
	        exit;
	}
}

?>
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,viewport-fit=cover">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />
    <title>自助注册</title>
    <script src="//cdn.bootcss.com/jquery/3.5.0/jquery.min.js"></script>
    <script type="text/javascript" src="//res.wx.qq.com/open/libs/weuijs/1.2.1/weui.min.js"></script>
<?php
if(preg_match('/wxwork\//', $_SERVER['HTTP_USER_AGENT'])) {
?>
    <link rel="stylesheet" href="//res.wx.qq.com/open/libs/weui/1.1.4/weui-for-work.min.css"/>
<?php
} else {
?>
    <link rel="stylesheet" href="//res.wx.qq.com/open/libs/weui/2.3.0/weui.min.css"/>
<?php
}
?>
</head>
<body>
<div class="page">
<?php
try {
if($_SERVER['REQUEST_METHOD']=='POST') {
	$sql_temp=
"SELECT personnel_v.SMT_SALARYNO, personnel_v.SMT_NAME, personnel_v.SMT_IDNO, personnel_v.SMT_SEX, TO_CHAR(personnel_v.SMT_BIRTHDAY, 'yyyy-MM-dd') AS SMT_BIRTHDAY, ".
"dept_v.SMT_DEPTNO, dept_v.SMT_DEPTNAME, card_v.SMT_ICCARDCODE, TO_CHAR(card_v.SMT_VALIDITYDATE, 'yyyy-MM-dd') AS SMT_VALIDITYDATE from personnel_v ".
"INNER JOIN DEPT_V ON personnel_v.SMT_DEPTCODE=DEPT_V.SMT_DEPTCODE ".
"INNER JOIN card_v on card_v.SMT_PERSONNELID=personnel_v.SMT_PERSONNELID AND card_v.smt_endcode=0 AND card_v.SMT_ICCARDCODE < 6 ".
"WHERE personnel_v.SMT_SALARYNO='%s' AND personnel_v.SMT_NAME='%s'";
	$dbh = new PDO("oci:dbname=//".$ecard_dbname.";charset=AL32UTF8", $ecard_user, $ecard_password);
	$sql=sprintf($sql_temp, $_POST['xgh'], $_POST['realname']);
	$ecard_result=$dbh->query($sql)->fetch(PDO::FETCH_ASSOC);
	$dbh=null;

	$sql_temp="SELECT READER.CERT_ID, READER.NAME, READER_CERT.REDR_CERT_ID FROM READER INNER JOIN READER_CERT ON READER.CERT_ID=READER_CERT.CERT_ID WHERE READER.CERT_ID='%s'";
	$sql=sprintf($sql_temp, $ecard_result['SMT_IDNO']);
	$dbh = new PDO("oci:dbname=//".$dbname.";charset=AL32UTF8", $dbuser, $dbpassword);
	$reader=$dbh->query($sql)->fetch(PDO::FETCH_ASSOC);

	if($reader!==FALSE) {
		if($reader['NAME']!==$_POST['realname'])
			throw new Exception(sprintf("读者库中已经存在证件号为 %s 的读者，但姓名不符。", $ecard_result['SMT_IDNO']));
		if($reader['REDR_CERT_ID']!==$_POST['xgh']) {
			$sql_temp="UPDATE READER_CERT SET REDR_CERT_ID='%s', END_DATE='%s', CERT_FLAG='1' WHERE CERT_ID='%s'";
			$sql=sprintf($sql_temp, $_POST['xgh'], $ecard_result['SMT_VALIDITYDATE'], $ecard_result['SMT_IDNO']);
			$code=$dbh->exec($sql);

			$sql_temp="UPDATE READER SET DEPT='%s', REDR_TYPE_CODE='%s', R_DEP_ID='' WHERE CERT_ID='%s'";
			$sql=sprintf($sql_temp, $ecard_result['SMT_DEPTNAME'], '03', $ecard_result['SMT_IDNO']);
			$code=$dbh->exec($sql);

			$sql=sprintf("SELECT DEP_ID FROM DEPARTMENT WHERE DEP_NAME='%s'", $ecard_result['SMT_DEPTNAME']);
			$r=$dbh->query($sql);
			if($r!==FALSE) {
				$depcode=$r->fetch(PDO::FETCH_ASSOC);
				$sql_temp="UPDATE READER SET R_DEP_ID='%s' WHERE CERT_ID='%s'";
				$sql=sprintf($sql_temp, $depcode['DEP_ID'], $ecard_result['SMT_IDNO']);
				$code=$dbh->exec($sql);
			}

			$sql_temp="call XT_LOG_DETL('42007', 'MWEI', '%s', '', '', '', '%s', '', '%s', '')";
			$sql=sprintf($sql_temp, $_SERVER['REMOTE_ADDR'], $ecard_result['SMT_IDNO'], $_POST['xgh']);
			$code=$dbh->exec($sql);

			$status=['code'=>'success', 'message'=>sprintf('已更新 %s (%s) 的读者条码', $_POST['realname'], $_POST['xgh'])];
		}
	} else {
		$sql_temp=
"INSERT INTO READER(CERT_ID, REDR_TYPE_CODE, LEND_GRD, ID_CARD, NAME, SEX, BIRTHDAY, DEPT, PASSWORD, REDR_REG_DAY, REDR_FLAG) ".
"VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '1')";
		$sql=sprintf($sql_temp, $ecard_result['SMT_IDNO'], '03', '01', $ecard_result['SMT_IDNO'], $ecard_result['SMT_NAME'], $ecard_result['SMT_SEX']=='男'?'M':'F',
			$ecard_result['SMT_BIRTHDAY'], $ecard_result['SMT_DEPTNAME'], $_POST['xgh'], date('Y-m-d')
		);
		$dbh->exec($sql);

		$sql=sprintf("call LT_READER_CERT('%s', '%s', '%s', '%s', '%s', %d, '1', '%s')",
			$ecard_result['SMT_SALARYNO'], $ecard_result['SMT_IDNO'], date('Y-m-d'), date('Y-m-d'), $ecard_result['SMT_VALIDITYDATE'], 0, 'MWEI'
		);
		$dbh->exec($sql);

		$sql=sprintf("SELECT DEP_ID FROM DEPARTMENT WHERE DEP_NAME='%s'", $ecard_result['SMT_DEPTNAME']);
		$r=$dbh->query($sql);
		if($r!==FALSE) {
			$depcode=$r->fetch(PDO::FETCH_ASSOC);
			$sql_temp="UPDATE READER SET R_DEP_ID='%s' WHERE CERT_ID='%s'";
			$sql=sprintf($sql_temp, $depcode['DEP_ID'], $ecard_result['SMT_IDNO']);
			$code=$dbh->exec($sql);
		}

		$sql_temp="call XT_LOG_DETL('42001', 'MWEI', '%s', '', '', '', '%s', '', '', '')";
		$sql=sprintf($sql_temp, $_SERVER['REMOTE_ADDR'], $ecard_result['SMT_IDNO']);
		$code=$dbh->exec($sql);

		$dbh = new PDO("oci:dbname=//".$ecard_dbname.";charset=AL32UTF8", $ecard_user, $ecard_password);
		$sql=sprintf("SELECT SMT_PHOTO FROM cardpersonnel_jp where SMT_SALARYNO='%s'", $_POST['xgh']);
		$stmt=$dbh->prepare($sql);
		$stmt->execute();
		$stmt->bindColumn('SMT_PHOTO', $photo, PDO::PARAM_LOB);
		$stmt->fetch(PDO::FETCH_BOUND);
		$r=stream_get_contents($photo);

		$dbh=null;
		$dbh=oci_connect($dbuser, $dbpassword, $dbname);
		$sql=sprintf("DELETE FROM READER_PORTRAIT WHERE P_CERT_ID='%s'", $ecard_result['SMT_IDNO']);
		$stmt=oci_parse($dbh, $sql);
		oci_execute($stmt, OCI_DEFAULT);
		oci_free_statement($stmt);

		$sql=sprintf("INSERT INTO READER_PORTRAIT(P_CERT_ID, REARDER_PORTRAIT) VALUES ('%s', :PHOTO)", $ecard_result['SMT_IDNO']);
		$stmt=oci_parse($dbh, $sql);
		oci_bind_by_name($stmt, ':photo', $r, -1, SQLT_LBI);
		oci_execute($stmt);
		oci_free_statement($stmt);
		oci_close($dbh);

		$status=['code'=>'success', 'message'=>sprintf('已新增读者 %s (%s)', $_POST['realname'], $_POST['xgh'])];
	}
?>
        <div class="page msg_<?php echo $status['code']; ?> js_show">
        <div class="weui-msg">
                <div class="weui-msg__icon-area"><i class="weui-icon-<?php echo $status['code']; ?> weui-icon_msg"></i></div>
                <div class="weui-msg__text-area"><p class="weui-msg__desc"><?php echo $status['message']; ?></p></div>
        </div>
        </div>
        <div class="weui-btn-area" style="display: none" id="close-button">
            <a class="weui-btn weui-btn_primary" href="javascript:WeixinJSBridge.call('closeWindow');">完成并关闭窗口</a>
        </div>
<script>
$(function(){
	$("#close-button").show();
});
</script>
<?php
} else {
	$sql_temp=
"SELECT READER.CERT_ID AS NUM FROM READER INNER JOIN READER_CERT ON READER.CERT_ID=READER_CERT.CERT_ID WHERE READER_CERT.REDR_CERT_ID='%s' AND READER.NAME='%s'";
	$sql=sprintf($sql_temp, $uid, $uname);
	$dbh = new PDO("oci:dbname=//".$dbname.";charset=AL32UTF8", $dbuser, $dbpassword);
	$results=$dbh->query($sql)->fetchAll();
	if(count($results)) throw new Exception(sprintf("读者信息库中已存在 %s (%s)", $uname, $uid), $results[0][0]);
	else $dbh=null;
	
	$sql_temp=
"SELECT personnel_v.SMT_SALARYNO, personnel_v.SMT_NAME, personnel_v.SMT_IDNO, personnel_v.SMT_SEX, TO_CHAR(personnel_v.SMT_BIRTHDAY, 'yyyy-MM-dd') AS SMT_BIRTHDAY, ".
"dept_v.SMT_DEPTNO, dept_v.SMT_DEPTNAME, card_v.SMT_ICCARDCODE from personnel_v ".
"INNER JOIN DEPT_V ON personnel_v.SMT_DEPTCODE=DEPT_V.SMT_DEPTCODE ".
"INNER JOIN card_v on card_v.SMT_PERSONNELID=personnel_v.SMT_PERSONNELID AND card_v.smt_endcode=0 AND card_v.SMT_ICCARDCODE < 6 ".
"WHERE personnel_v.SMT_SALARYNO='%s' AND personnel_v.SMT_NAME='%s'";
	$dbh = new PDO("oci:dbname=//".$ecard_dbname.";charset=AL32UTF8", $ecard_user, $ecard_password);
	$sql=sprintf($sql_temp, $uid, $uname);
	$results=$dbh->query($sql)->fetchAll();
	if (count($results)>0) {
?>
<div class="list input">
	<div class="page__bd">
		<div class="weui-cells__title">来自一卡通数据库的信息</div>
		<div class="weui-cells">
			<div class="weui-cell">
				<div class="weui-cell__bd">一卡通号</div>
				<div class="weui-cell__ft"><?php echo $results[0]['SMT_SALARYNO']; ?></div>
			</div>
			<div class="weui-cell">
				<div class="weui-cell__bd">姓名</div>
				<div class="weui-cell__ft"><?php echo $results[0]['SMT_NAME']; ?></div>
			</div>
			<div class="weui-cell">
				<div class="weui-cell__bd">身份证号</div>
				<div class="weui-cell__ft"><?php echo $results[0]['SMT_IDNO']; ?></div>
			</div>
			<div class="weui-cell">
				<div class="weui-cell__bd">性别</div>
				<div class="weui-cell__ft"><?php echo $results[0]['SMT_SEX']; ?></div>
			</div>
			<div class="weui-cell">
				<div class="weui-cell__bd">出生日期</div>
				<div class="weui-cell__ft"><?php echo empty($results[0]['SMT_BIRTHDAY'])?substr($results[0]['SMT_IDNO'], 6, 8):$results[0]['SMT_BIRTHDAY']; ?></div>
			</div>
			<div class="weui-cell">
				<div class="weui-cell__bd">部门</div>
				<div class="weui-cell__ft"><?php echo $results[0]['SMT_DEPTNAME']; ?></div>
			</div>
		</div>
		<label for="weuiAgree" class="weui-agree">
			<input id="weuiAgree" type="checkbox" class="weui-agree__checkbox"> <span class="weui-agree__text">我已知，数据不同步是因为相关职能部门的数据未传送到中心库，并授权图书馆从一卡通数据库中读取我的信息和照片。</span>
		</label>
		<div class="weui-btn-area">
			<a class="weui-btn weui-btn_primary weui-btn_disabled" href="#" id="btnSubmit">立即注册激活</a>
		</div>
		<form id="dataform"  method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
			<input type="hidden" name="xgh" value="<?php echo $results[0]['SMT_SALARYNO']; ?>">
			<input type="hidden" name="realname" value="<?php echo $results[0]['SMT_NAME']; ?>">
		</form>
	</div>
</div>
<script>
$(function() {
	$("#btnSubmit").addClass('weui-btn_disabled');
	$("#weuiAgree").prop('checked', false);
	$("#weuiAgree").change(function () {
		$("#btnSubmit").toggleClass("weui-btn_disabled");
	});

	$("#btnSubmit").click(function (event) {
		event.preventDefault();
		if($("#btnSubmit").hasClass("weui-btn_disabled"))
			return;
		else $("#dataform").submit();
		
	});
	weui.alert('正常情况下，图书馆的读者信息会从学院人员信息库(来自于教务系统、人事系统)自动同步。如相应系统的数据缺失或不完善，将会导致同步失败，需要读者手工注册。', { buttons: [{label: '我知道了', type: 'primary'}]});
});
</script>
<?php
	} else {
?>
	<div class="page msg_info js_show">
	<div class="weui-msg">
		<div class="weui-msg__icon-area"><i class="weui-icon-info weui-icon_msg"></i></div>
		<div class="weui-msg__text-area"><h2 class="weui-msg__title">无数据</h2><p class="weui-msg__desc">在一卡通数据库里找不到 <?php echo sprintf("%s (%s) ",$uname, $uid); ?> 的信息。</p></div>
		<div class="weui-msg__extra-area">
			<div class="weui-footer"><p class="weui-footer__links"><a href="https://eaiapp.ccom.edu.cn/site/center/switch" class="weui-footer__link">如需切换身份请点击此处</a></p></div>
	        </div>
	</div>
	</div>
<?php
	}
	}

} catch (Exception $e) {
?>
	<div class="page msg_info js_show">
	<div class="weui-msg">
		<div class="weui-msg__icon-area"><i class="weui-icon-warn weui-icon_msg"></i></div>
		<div class="weui-msg__text-area"><h2 class="weui-msg__title">错误</h2><p class="weui-msg__desc"><?php echo sprintf("%s", $e->getMessage()); ?></p></div>
		<div class="weui-msg__extra-area">
			<div class="weui-footer"><p class="weui-footer__links"><a id="switch-identify" href="https://eaiapp.ccom.edu.cn/site/center/switch" class="weui-footer__link">如需切换身份请点击此处</a></p></div>
		</div>
	</div>
	</div>
<script>
$(function() {
	$('#switch-identify').click(function (event) {
		event.preventDefault();
		weui.alert('切换身份时，密码请尝试身份证号后六位，Ccom+身份证号后六位，或 Ccom+一卡通号数字部分(如WP1903，则密码可能为Ccom1903)。', {
			buttons: [{
				label: '好的',
				type: 'primary',
				onClick: function(){ window.location="https://eaiapp.ccom.edu.cn/site/center/switch"; }
			}]
		});
	});
});
</script>
<?php
} finally {
	$dbh=null;
}
?>
</div>
</body>
</html>
